import xlrd
from utils import utils
from model import cell_data
from model import sheet_obj
from template.typescript import template_ts
import json
class excel_builder:
    def __init__(self,path,args) -> None:
        self.file_path = path
        self.sheet_datas = {}
        self.sheet_objs = {}
        self.args = args
        self.out_bin_dir = args["out_bin"]
        self.out_model_dir = args["out_model"]
        self.build_type = args["type"]
        

    def load(self):
        self.workbook = xlrd.open_workbook(self.file_path)
        
        for sheet_name in self.workbook.sheet_names():
            if sheet_name[0] == "_":
                continue
            self.build_sheet(self.workbook.sheet_by_name(sheet_name),sheet_name)
    
    def build_sheet(self,sheet,sheetname):


        self.output_model(sheet,sheetname)

        self.output_bin(sheet,sheetname)



    def output_model(self,sheet,sheetname):
        name_values = sheet.row_values(0)
        type_values = sheet.row_values(1)
        self.key_type = type_values[0]
        self.sheet_objs[sheetname] = sheet_obj.sheet_obj(sheetname,type_values,name_values)

        template = None
        if self.build_type == "ts":
            template = template_ts.template_ts(self.sheet_objs[sheetname])
        if template:
            template.build()
            template.save(self.out_model_dir)
    #输出文档数据
    def output_bin(self,sheet,sheetname):
        cow_len = sheet.ncols
        name_values = sheet.row_values(0)
        type_values = sheet.row_values(1)

        self.sheet_datas[sheetname] = {}

        for row_y in range(2,sheet.nrows):
            row_values = sheet.row_values(row_y)
            index = row_y - 2
            key_value = row_values[0]
            if self.sheet_objs[sheetname].key_type == "number":
                key_value = int(key_value)
            self.sheet_datas[sheetname][key_value] = {}

            for col_x in range(0,cow_len):
                value = row_values[col_x]
                value_type = type_values[col_x]
                value_name = name_values[col_x]
                celldata = cell_data.cell_data(value_type,value)
                if celldata.verify():
                    self.sheet_datas[sheetname][key_value][value_name] = celldata.value
                else:
                    print("value error")

        jsonstr = json.dumps(self.sheet_datas[sheetname])

        utils.writeFile(self.out_bin_dir + f"/bin_Cfg{sheetname}.json",jsonstr)
        
        


